<template>
  <div class="workbench-home">
    <div class="flex-card-box">
      <div class="top-box">
        <div :class="`column-cls ${item.cls}`" v-for="(item, index) in columnList" :key="'column-cls_' + index">
          <div>
            <div class="c-c-t">{{ item.name }}</div>
            <div class="c-c-n">{{ item.num }}</div>
          </div>
          <div :class="`icon-wh-cls${index + 1} i-size`"></div>
        </div>
      </div>
    </div>
    <div class="flex-card-box">
      <div style="display: flex;padding: 1rem;">
        <div class="project-card" v-loading="eeLoading">
          <div class="project-item" v-for="(item, index) in projectList" :key="'project-item_' + index"
            @click="wsStore.setProject(item)">
            <div :class="item.id === selectId ? 'card-front' : 'card-front-no'">
              <div class="project-item-title">{{ item.projectName }}</div>
              <div class="project-item-content">
                <div class="project-item-content-item">
                  <div class="project-item-content-item-title">{{ i18n.fy.Totaldevices }}</div>
                  <div class="project-item-content-item-num">{{ item.lightFixtureCount }}</div>
                </div>
              </div>
            </div>
          </div>
          <el-popover v-if="wsStore.projectList.length > 3" class="workbench-home-project-popover" placement="bottom"
            width="20%" trigger="click">
            <template #reference>
              <div class="project-item-sle" @click="selectShowProject = true">
                <div class="card-front-sle" v-if="projectSleIds.indexOf(wsStore.project.id) !== -1">
                  <div>
                    更多选择项目...
                  </div>
                </div>
                <div class="card-front" v-else>
                  <div class="project-item-title">{{ wsStore.project.projectName }}</div>
                  <div class="project-item-content">
                    <div class="project-item-content-item">
                      <div class="project-item-content-item-title">{{ i18n.fy.Totaldevices }}</div>
                      <div class="project-item-content-item-num">{{ wsStore.project.lightFixtureCount }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
            <el-input v-model="inputName" size="large" placeholder="请输入项目名称" :suffix-icon="Search" />
            <div class="my-elm-select">
              <div :class="item.id === selectId ? 'my-elm-select-item my-elm-selected' : 'my-elm-select-item'"
                v-for="(item, index) in projectSleList" :key="'my-elm-select-item_' + index"
                @click="wsStore.setProject(item)">
                <div style="display: flex; justify-content: space-between;">
                  <span>{{ item.projectName }}</span>
                  <div :class="item.id === selectId ? 'my-elm-select-item-icon' : ''"></div>
                </div>
              </div>
            </div>
          </el-popover>
        </div>
        <div class="base-info">
          <div class="base-info-item" v-for="(item, index) in columnInfoList" :key="'base-info-item_' + index">
            <div :class="'base-info-item-icon-' + index"></div>
            <div>
              <div class="base-info-item-title">{{ item.name }}</div>
              <div class="base-info-item-num">{{ item.num }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-card-box">
      <div class="bottom-box">
        <div class="row-cls" v-for="(item, index) in rowList" :key="'row-cls_' + index">
          <div class="r-c-l">
            <div class="r-c-l-h" style="display: flex; justify-content: space-between;">
              <div>
                <span>{{ item.name }} ( {{ wsStore.project.projectName }} )</span>
              </div>
              <div class="heder-btn">
                <span>{{ i18n.fy.无线设备 }} </span>
              </div>
            </div>
            <div class="" :id="`echart_radar_custom_${index}`" style="width: 100%; height: 100%">
            </div>
          </div>
          <div class="r-c-r">
            <div class="r-c-l-h" style="display: flex; justify-content: space-between;">
              <div>
                <span> {{ i18n.fy.能耗信息统计 }} ( {{ wsStore.project.projectName }} )</span>
              </div>
              <div style="display: flex;">
                <div class="heder-btn" @click="changeTime()">
                  <span>{{ sTime }}</span> 至 <span>{{ eTime }}</span>
                </div>
                <el-switch v-model="isRealMeter"
                  style="--el-switch-on-color: #2139bd; --el-switch-off-color: #367351;height: auto; margin-left: 0.5rem;"
                  inline-prompt :active-text="rmText" :inactive-text="rmText" @change="changeRealMeter"
                  :loading="eeLoading" />
              </div>
            </div>
            <div :id="`echart_energy_${index}`" style="width: 100%; height: 90%" v-loading="eeLoading">
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-card-box" style="flex: 1;margin-bottom: 1rem;">
      <div class="bottom-card">
        <div class="f-b-h">物联网设备网关信息（{{ wsStore.project.projectName }}）
        </div>
        <div style="width: 100%;">
          <div class="table-title">
            <div class="table-title-cell" v-for="(item, index) in tableTitle" :key="'table-title_' + index">{{ item }}
            </div>
          </div>
          <div class="table-content">
            <div class="table-row" v-for="(item, index) in tableData" :key="'table-row_' + index">
              <div class="table-row-cell" v-for="(key, index2) in tableTitle"
                :key="'table-title-cell_' + index + '-' + index2">
                <span :class="tecCls(item, key)"> {{ item[key] }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogOverflowVisible" :show-close="false" width="500" :modal="false">
      <template #header="{ colse }">
        <div class="dialog-header-box">
          <div class="dialog-header-text">{{ title }}</div>
          <el-button type="primary" @click="confirmSelection()">
            <el-icon class="el-icon--left dialog-header-icon">
              <Checked />
            </el-icon>
            {{ i18n.fy.confirm }}
          </el-button>
        </div>
      </template>
      <el-date-picker v-model="timeArr" type="daterange" :range-separator="i18n.fy.至" :start-placeholder="i18n.fy.开始时间"
        :end-placeholder="i18n.fy.结束时间" :size="size" :disabled-date="disabledDate" format="YYYY/MM/DD"
        value-format="YYYY-MM-DD" />
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
import { workbenchScreenStore } from "@/pinia/workbenchScreen";
const wsStore = workbenchScreenStore();
import { getQuantityStatistics, getProjectInfo } from '@/api/homepageApi'
import optJson from './echarts.json';
import rcoptJson from './echarts_radar_custom.json';
import * as echarts from "echarts";
const { appContext: { config: { globalProperties } } } = getCurrentInstance()
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import { watch } from 'vue';

defineOptions({ name: 'WorkbenchHome' })
const title = ref('标题')
const dialogOverflowVisible = ref(false)
const size = ref('default')
const sTime = ref(globalProperties.$dayjs().startOf('month').format('YYYY-MM-DD'))
const eTime = ref(globalProperties.$dayjs().format('YYYY-MM-DD'))
const timeArr = ref([sTime.value, eTime.value])
let myChart = null
let myChartLD = null
const dateList = ref([])
let eeLoading = ref(false)
const columnListNumData = ref([])
const selectShowProject = ref(false)
const inputName = ref('')
const tableTitle = ref(['nickname', 'activeTime', 'areaCode', 'createTime', 'deviceName', 'deviceSecret', 'deviceStatus', 'iotId', 'ipAddress', 'lastOnlineTime', 'productKey', 'productName'])
let isRealMeter = ref(true)
let rmText = ref('能耗信息')

const tableData = computed(() => {
  if (wsStore.project && wsStore.project.iotDeviceList) {
    return wsStore.project.iotDeviceList
  }
  return []
})

watch(() => wsStore.projectId, (newValue, oldValue) => {
  console.log(newValue, oldValue);
  getQSList()
})

watch(() => inputName, (nval, oval) => {
  let arr = []
  console.log('nval->', nval);
  // wsStore.projectList.forEach(element => {
  //   if (element.projectName.indexOf(nval) !== -1) {
  //     arr.push(element)
  //   }
  // });
  // projectSleList = arr
})

const projectSleList = computed(() => {
  return wsStore.projectList
})

const projectList = computed(() => {
  let arr = []
  wsStore.projectList.forEach((item, index) => { if (index < 3) { arr.push(item) } })
  return arr
})

const projectSleIds = computed(() => {
  let arr = []
  wsStore.projectList.forEach((item, index) => { if (index < 3) { arr.push(item.id) } })
  return arr
})

const selectId = computed(() => { return wsStore.project.id })

const columnInfoList = computed(() => {
  return [
    { id: 1, name: '改造前累计电量/kwh', num: wsStore.project.baselineEnergy, cls: 'column-cls1' },
    { id: 2, name: '本月节能/kwh', num: wsStore.project.monEnergySaving, cls: 'column-cls2' },
    { id: 3, name: '本年节能/kwh', num: '0.00', cls: 'column-cls3' },
    { id: 4, name: '累计节能/kwh', num: '0.00', cls: 'column-cls4' },
    { id: 5, name: '累计减碳排放量/kg', num: '0.00', cls: 'column-cls5' }
  ]
});

const columnList = computed(() => {
  return [
    { id: 1, name: i18n.fy.projectsTotal, num: columnListNumData.value[0], cls: 'column-cls1' },
    { id: 2, name: i18n.fy.当前项目, num: wsStore.project.projectName, cls: 'column-cls2' },
    { id: 3, name: i18n.fy.项目收益, num: columnListNumData.value[2], cls: 'column-cls3' },
    { id: 4, name: i18n.fy.Totaldevices, num: columnListNumData.value[3], cls: 'column-cls4' },
    { id: 5, name: i18n.fy.esr, num: columnListNumData.value[4], cls: 'column-cls5' }
  ]
});

const rowList = computed(() => {
  return [{ id: 1, name: i18n.fy.研发产品智能场景雷达图 }]
});

const tecCls = (item, key) => {
  let cls = ''
  if (key === 'deviceStatus') {
    if (item[key] === 'OFFLINE') {
      cls = 'tec-cls-offline'
    } else {
      cls = 'tec-cls-line'
    }
  }
  return cls
}

const changeRealMeter = (val) => {
  getQSList()
  rmText.value = val ? i18n.fy.能耗信息 : i18n.fy.电表电量
}

const getProjectList = async () => {
  let res = await getProjectInfo()
  if (res.length > 0) {
    wsStore.setProjectList(res)
    columnListNumData.value.push(res.length + '个')
    columnListNumData.value.push(res[0].projectName)
    columnListNumData.value.push(res[0].investmentAmount * res[0].energyEfficiency + '万元')
    columnListNumData.value.push(res[0].lightFixtureCount + '个')
    columnListNumData.value.push(res[0].energyEfficiency + '%')
    console.log('columnListData', columnListNumData.value);
    getQSList()
  } else {
    wsStore.setProjectList([])
  }
}

const getQSList = async () => {
  let poms = {
    start: sTime.value + ' 00:00:00',
    end: eTime.value + ' 00:00:00',
    projectIds: wsStore.projectId,
    isRealMeter: !isRealMeter.value,
    mode: 1
  }
  eeLoading.value = true
  let oval = await getQuantityStatistics(poms)
  eeLoading.value = false
  if (oval.code === 200) {
    dateList.value = [[], []]
    oval.data.forEach(element => {
      dateList.value[0].push(element._id)
      dateList.value[1].push(element.totalDiff)
    });
  }
  renderingChart()
}

const renderingChart = () => {
  const obj = { ...optJson }
  obj.xAxis[0].data = dateList.value[0]
  obj.series[0].data = dateList.value[1]
  obj.yAxis[0].name = '单位（kwh）'
  obj.title = []
  obj.toolbox.feature.dataView.optionToContent = function (opt) {
    var axisData = opt.xAxis[0].data; //坐标轴
    var series = opt.series; //折线图的数据
    var tdHeads = '<td style="margin-top:10px; padding: 10px 15px">时间</td>';
    var tdBodys = "";
    series.forEach(function (item) { tdHeads += `<td style="padding:5px 15px">能耗值(kwh)</td>`; });
    var table = `<table border="1" style="width:90%;margin-left:20px;border-collapse:collapse;font-size:14px;text-align:center" id="table-content"><tbody><tr>${tdHeads} </tr>`;
    for (var i = 0, l = axisData.length; i < l; i++) {
      for (var j = 0; j < series.length; j++) {
        if (series[j].data[i] == undefined) {
          tdBodys += `<td>${"-"}</td>`;
        } else {
          tdBodys += `<td>${series[j].data[i]}</td>`;
        }
      }
      table += `<tr><td style="padding: 15px 20px">${axisData[i]}</td>${tdBodys}</tr>`;
      tdBodys = "";
    }
    table += "</tbody></table>";
    return table;
  }
  obj.toolbox.feature.dataView.contentToOption = function (HTMLDomElement, opt) {
    console.log("导出按钮->");
    //此处传入table的DOM节点
    let et = XLSX.utils.table_to_book(document.getElementById("table-content"));
    let etout = XLSX.write(et, { bookType: "xlsx", bookSST: true, type: "array" });
    console.log('etout->', etout);
    try {
      FileSaver.saveAs(new Blob(
        [etout],
        { type: "application/octet-stream" }),
        `${wsStore.project.projectName}_${sTime.value}至${eTime.value}_${rmText.value}统计数据.xlsx`
      );
    } catch (e) { }
    return etout;
  }

  if (myChart) {
    myChart.setOption(obj);
  }

}

const confirmSelection = () => {
  // 关闭弹窗
  dialogOverflowVisible.value = false
  // 重置echart图表
  eeLoading.value = true
  sTime.value = `${timeArr.value[0]}`
  eTime.value = `${timeArr.value[1]}`
  // 请求接口数据
  getQSList()
}

const changeTime = () => {
  title.value = '能耗信息时间选择'
  dialogOverflowVisible.value = true
}

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

onMounted(() => {
  getProjectList()

  let doc = document.getElementById('echart_energy_0')
  if (doc) {
    myChart = echarts.init(doc);
  }

  let docLD = document.getElementById('echart_radar_custom_0')
  if (docLD) {
    myChartLD = echarts.init(docLD);
    const optionLD = { ...rcoptJson }
    myChartLD.setOption(optionLD);
  }
})

</script>
<style lang="scss">
.el-date-table td.prev-month.disabled .el-date-table-cell {
  color: #fff !important;
  background-color: #f4f4f5 !important;
}

.el-date-table td.normal.disabled .el-date-table-cell {
  color: #fff !important;
  background-color: #f4f4f5 !important;
}

.el-date-table td.next-month.disabled .el-date-table-cell {
  color: #fff !important;
  background-color: #f4f4f5 !important;
}
</style>

<style lang="scss" scoped>
.workbench-home {
  width: 100%;
  display: flex;
  background-color: #383838;
  flex-direction: column;

  .base-info {
    font-size: 17px;
    width: 100%;
    background-color: #1c1c1c;
    display: flex;
    justify-content: space-around;
    color: #fff;
    padding: 1.5rem;

    .base-info-item {
      flex-direction: row;
      justify-items: center;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .base-info-item-r {
      border-left: 1px solid #383838;
    }

    .base-info-item-icon-0 {
      background: url(/src/assets/icon/w-h-p_4.png) center no-repeat;
      width: 64px;
      height: 64px;
    }

    .base-info-item-icon-1 {
      background: url(/src/assets/icon/w-h-p_4.png) center no-repeat;
      width: 64px;
      height: 64px;
    }

    .base-info-item-icon-2 {
      background: url(/src/assets/icon/w-h-p_4.png) center no-repeat;
      width: 64px;
      height: 64px;
    }

    .base-info-item-icon-3 {
      background: url(/src/assets/icon/w-h-p_4.png) center no-repeat;
      width: 64px;
      height: 64px;
    }

    .base-info-item-icon-4 {
      background: url(/src/assets/icon/w-h-p_4.png) center no-repeat;
      width: 64px;
      height: 64px;
    }
  }

  .project-card {
    display: flex;
    -webkit-flex-wrap: nowrap;
    flex-wrap: nowrap;
    padding-bottom: 1rem;

    .project-item-sle {
      width: 14rem;
      height: 10rem;
    }

    .project-item {
      width: 14rem;
      height: 11rem;
    }

    .card-front-sle {
      position: absolute;
      width: 10rem;
      height: 10rem;
      border-radius: 1rem;
      background-color: #1c1c1c;
      transition: box-shadow 0.3s ease;
      padding: 1rem;
      color: #fff;
    }

    .card-front-sle:hover {
      box-shadow: 0 8px 16px #4c575e;
    }

    .card-front-no {
      position: absolute;
      width: 10rem;
      height: 10rem;
      border-radius: 1rem;
      background-color: #1c1c1c;
      transition: box-shadow 0.3s ease;
      padding: 1rem;
      color: #fff;
    }

    .card-front-no:hover {
      box-shadow: 0 8px 16px #4c575e;
    }

    .card-front {
      position: absolute;
      color: #fff;
      width: 10rem;
      height: 10rem;
      border-radius: 1rem;
      background-color: #1c1c1c;
      transition: box-shadow 0.3s ease;
      padding: 1rem;
      backface-visibility: hidden;
      overflow: hidden;
    }

    .card-front:before {
      position: absolute;
      top: -6rem;
      right: -6rem;
      content: '';
      width: 10rem;
      height: 10rem;
      background-color: #428bd4;
      transform: rotate(45deg);
      z-index: 1;
    }

    .card-front:after {
      position: absolute;
      content: '';
      top: 5px;
      right: 5px;
      z-index: 2;
      background: url(/src/assets/icon/w-h-p_4.png) center no-repeat;
      width: 32px;
      height: 32px;
    }

    .card-front:hover {
      box-shadow: 0 8px 16px #4c575e;
    }
  }

  .flex-card-box {
    background-color: #383838;
  }

  .bottom-card {
    margin: 0px 1rem;
    height: 100%;
    background-color: #333b54;
    display: flex;

    .f-b-h {
      font-weight: bold;
      color: #c3c3c3;
      width: 2rem;
      background-color: #212121;
      border-left: 1px solid rgba(0, 0, 0, 0.03);
      padding: 0.8rem;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      writing-mode: vertical-lr;
    }

    .table-title {
      display: flex;
      justify-content: space-around;
      width: 100%;
      height: 4rem;
      line-height: 4rem;
      border-bottom: #0b4b7d 1px solid;
      background-color: #1f2037;
      color: #fff;

    }

    .table-title-cell {
      text-align: center;
      width: 10rem;
    }

    .table-content {
      height: 26.66vh;
      overflow: auto;
    }

    .table-row {
      width: 100%;
      height: 3.5rem;
      line-height: 3.5rem;
      background-color: #333b54;
      border-bottom: #0b4b7d 1px solid;
      color: #fff;
      display: flex;
      justify-content: space-around;
    }

    .table-row-cell {
      width: 10rem;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .tec-cls-offline {
      background-color: #FF4961;
      color: #FFFFFF;
      font-weight: 400;
      padding: 0.5rem;
      border-radius: 1rem;
      user-select: none;
    }

    .tec-cls-line {
      padding: 0.5rem;
      border-radius: 1rem;
      background-color: #28D094;
      color: #FFFFFF;
      font-weight: 400;
      user-select: none;
    }
  }

  .heder-btn {
    user-select: none;
    cursor: pointer;
    color: #2196f3;
  }

  :deep(.el-dialog) {
    background-color: #0b4b7d;
  }

  :deep(.el-dialog .el-dialog__header) {
    padding: 0;
  }

  :deep(.el-dialog .el-dialog__body) {
    padding: 10px 0px;
  }

  :deep(.el-range-editor.el-input__wrapper) {
    padding: 0;
    width: 100%;
  }

  :deep(.el-dialog__body .el-date-editor .el-range__icon) {
    width: 40px;
  }

  .dialog-header-icon {
    width: 40px;
  }

  .dialog-header-text {
    margin-left: 1rem;
    font-size: 16px;
  }

  .dialog-header-box {
    display: flex;
    justify-content: space-between;
    background-color: #0b4b7d;
    color: #fff;
  }

  .icon-wh-cls1 {
    background: url(/src/assets/icon/icon-w-h-2.png) center no-repeat;
    background-size: cover;
  }

  .icon-wh-cls2 {
    background: url(/src/assets/icon/xmdw_01.png) center no-repeat;
    background-size: cover;
  }

  .icon-wh-cls3 {
    background: url(/src/assets/icon/icon-w-h-1.png) center no-repeat;
    background-size: cover;
  }

  .icon-wh-cls4 {
    background: url(/src/assets/icon/icon-w-h-4.png) center no-repeat;
    background-size: cover;
  }

  .icon-wh-cls5 {
    background: url(/src/assets/icon/icon-w-h-3.png) center no-repeat;
    background-size: cover;
  }

  .i-size {
    width: 50px;
    height: 50px;
    margin-top: 10px;
  }

  .top-box {
    display: flex;
    flex-wrap: wrap;
    margin-right: 15px;
  }

  .bottom-box {
    padding-left: 15px;
  }

  .column-cls {
    flex: 1 1 auto;
    padding: 30px;
    box-shadow: 0 0 13px 0 rgba(82, 63, 105, 0.1);
    border: none;
    border-radius: 3px;
    background-color: #171717;
    margin: 15px 0 0 15px;
    display: flex;
    justify-content: space-between;
    color: #fff;

    .c-c-t {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
    }

    .c-c-n {
      font-size: 16px;
      font-weight: bolder;
    }
  }

  .row-cls {
    height: 33.33rem;
    background-color: #383838;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1019607843);
    margin-bottom: 0.25rem;
    margin-right: 15px;
    display: flex;

    .r-c-l {
      width: 40%;
      background-color: #171717;
      margin-right: 0.2rem;
    }

    .r-c-r {
      width: 100%;
      background-color: #171717;
    }
  }

  .r-c-l-h {
    font-weight: bold;
    border-bottom: 1px solid rgba(0, 0, 0, 0.03);
    background-color: #212121;
    color: #fff;
    height: 1.5rem;
    padding: 0.8rem;
    font-size: 1rem;
  }
}
</style>
